package com.baiyinet.ui.splash;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baiyinet.BuildConfig;
import com.baiyinet.MyApp;
import com.baiyinet.R;
import com.baiyinet.biz.AdInfo;
import com.baiyinet.biz.CurrentUser;
import com.baiyinet.di.DaggerScope;
import com.baiyinet.di.Injector;
import com.baiyinet.rest.ApiHelper;
import com.baiyinet.rest.AppInfo;
import com.baiyinet.util.IntentUtils;
import com.baiyinet.util.Utils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.FadeEnter.FadeEnter;
import com.flyco.animation.FadeExit.FadeExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.umeng.analytics.MobclickAgent;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Fullscreen;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;

import java.util.ArrayList;
import java.util.Random;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import cn.jpush.android.api.JPushInterface;
import myandroid.library.util.ApplicationHelper;
import rx.Subscriber;

import static com.baiyinet.Constants.AD_SHOW_SECOND;

@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(SplashActivity.class)
@Fullscreen
@EActivity(R.layout.activity_splash)
public class SplashActivity extends Activity {

    @Inject
    ApiHelper mApiHelper;
    @Inject
    CurrentUser mCurrentUser;
    @Inject
    SharedPreferences mSharedPreferences;

    @ViewById(R.id.activity_splash_layout_ad)
    RelativeLayout layoutAd;

    @ViewById(R.id.open_ad_tv_num)
    TextView mNumText;
    @ViewById(R.id.open_ad_layout_backgroud)
    RelativeLayout mOpenAdLayout;

    @StringRes(R.string.network_disabled)
    String strNetworkDisabled;
    @StringRes(R.string.api_error)
    String strApiError;
    @StringRes(R.string.https_error)
    String strHttpsError;

    @ViewById(R.id.imv_splash_background)
    ImageView ivBackground;

    private static final int APP_PERMISSION = 100;
    private boolean checkPermission = true;

    private String mAdUrl = "";
    private int mAdCountDownSecond = AD_SHOW_SECOND;

    private NormalDialog mDialog;

    Subscriber<AppInfo> mSubscriber;

    private final int MSG_CODE_SHOW_AD = 111;
    private final int MSG_CODE_AD_COUNT_DOWN = 222;

    @AfterInject
    void initDI() {
        Injector.initSplashActivityComponent().inject(this);
    }


    public void onResume() {
        super.onResume();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                    ) {

                if (checkPermission) {
                    // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义)
                    requestPermissions(new String[]{
                            Manifest.permission.INTERNET,
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.ACCESS_NETWORK_STATE,
                            Manifest.permission.ACCESS_WIFI_STATE,
                            Manifest.permission.CHANGE_WIFI_STATE,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.CAMERA,
                    }, APP_PERMISSION);
                    return;
                }
            }
        }

        getAppInfo();
        JPushInterface.onResume(this);
        MobclickAgent.onResume(this);   //统计时长
    }

    public void onPause() {
        JPushInterface.onPause(this);
        MobclickAgent.onPause(this);

        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mSubscriber != null) {
            mSubscriber.unsubscribe();
            mSubscriber = null;
        }
        if (mDialog != null) {
            mDialog.superDismiss();
            mDialog = null;
        }

        if (mMsgHandler != null) {
            mMsgHandler.removeCallbacksAndMessages(null);
        }

        super.onDestroy();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }

    @Override
    public void onBackPressed() {}

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        checkPermission = false;

        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case APP_PERMISSION:
                boolean granted = true;
                for (int i : grantResults) {
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        granted = false;
                        break;
                    }
                }

                if (!granted) {
                    // 没有获取到权限，做特殊处理
                    Utils.UI.showToastLong("应用权限不足，部分功能无法使用\n请稍后在\"设置\"中开启权限");
                }
                break;
            default:
                break;
        }
    }

    @Background(delay = 5000)
    void delayToFinishApp() {
        Utils.App.clearCache(this);
        finish();
        ApplicationHelper.getInstance().exit();
    }

    void getAppInfo() {
        if (!Utils.Network.isNetworkAvailable()) {
            showCancelDialog();
            return;
        }

        mSubscriber = new AppInfoSubscriber();
        mApiHelper.getAppInfo(mSubscriber);
    }

    @Background(delay = 2000)
    void delayToNextPage() {
        toNextPage("");
    }

    void toNextPage(String adUrl) {
        mCurrentUser.setAppLastUsedTime(SystemClock.elapsedRealtime());

        if (mCurrentUser.hasLoggedIn()) {
            IntentUtils.toMain(this, adUrl);
        } else {
            IntentUtils.toLogin(this);
        }

        finish();
    }

    private void showCancelDialog() {
        BaseAnimatorSet bas_in = new FadeEnter();
        BaseAnimatorSet bas_out = new FadeExit();
        mDialog = new NormalDialog(this);

        mDialog.isTitleShow(false)
                .btnNum(1)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content("当前网络不可用,请检查你的网络设置")
                .contentGravity(Gravity.CENTER)
                .contentTextSize(13)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText("确定")
                .btnTextSize(15.5f, 15.5f)
                .btnTextColor(Color.parseColor("#0092FF"))
                .widthScale(0.7f)
                .showAnim(bas_in)
                .dismissAnim(bas_out)
                .show();

        mDialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
                startActivity(intent);

                Utils.App.clearCache(SplashActivity.this);
                finish();
                ApplicationHelper.getInstance().exit();
            }
        });
    }

    private void initBaiduAd() {
//        AdBaiduSplash splash = new AdBaiduSplash(this, "4588225", mOpenAdLayout);
//        splash.setAdListener(new AdBaiduSplashListener() {
//            @Override
//            public void onAdLoaded() {
//
//            }
//
//            @Override
//            public void onAdFailed() {
//
//            }
//
//            @Override
//            public void onAdClose() {
//
//            }
//
//            @Override
//            public void onAdClick() {
//
//            }
//        });

//        handler.sendEmptyMessageDelayed(MSG_CODE_AD_COUNT_DOWN, 1000);
        delayToNextPage();
    }

    private void initAdInfo(AdInfo adInfo) {
        mNumText.setText(String.valueOf(AD_SHOW_SECOND));

        ArrayList<AdInfo.AdDetail> data = adInfo.getData();
        int total = adInfo.getData().size();
        String imgUrl;
        if (total > 1) {
            Random random = new Random();
            int randomIndex = random.nextInt(data.size());
            mAdUrl = data.get(randomIndex).getUrl();
            imgUrl = data.get(randomIndex).getImage();
        } else {
            mAdUrl = data.get(0).getUrl();
            imgUrl = data.get(0).getImage();
        }

        if (!TextUtils.isEmpty(mAdUrl) && !mAdUrl.startsWith("http") && !mAdUrl.startsWith("#")) {
            mAdUrl = BuildConfig.ENDPOINT + mAdUrl;
        }

        if (!imgUrl.startsWith("#") && !imgUrl.startsWith("http")) {
            imgUrl = BuildConfig.ENDPOINT + imgUrl;
        }

        ImageView imageView = new ImageView(this);

        imageView.setScaleType(ImageView.ScaleType.CENTER);

        DisplayMetrics dm = getResources().getDisplayMetrics();

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                dm.widthPixels,
                dm.heightPixels);

        mOpenAdLayout.addView(imageView, params);

        Glide
                .with(this)
                .load(imgUrl)
                .skipMemoryCache(false)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .centerCrop()
                .into(imageView);


        // 为了让图片先加载一会
        mMsgHandler.sendEmptyMessageDelayed(MSG_CODE_SHOW_AD, 1000);
    }

    private Handler mMsgHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_CODE_AD_COUNT_DOWN:
                    mAdCountDownSecond--;
                    if (mAdCountDownSecond > 0) {
                        mNumText.setText(String.valueOf(mAdCountDownSecond));
                        mMsgHandler.sendEmptyMessageDelayed(MSG_CODE_AD_COUNT_DOWN, 1000);
                    } else {
                        toNextPage("");
                    }
                    break;
                case MSG_CODE_SHOW_AD:
                    countdownShowAd();
                    break;
                default:
                    break;
            }
        }
    };

    void countdownShowAd() {
        layoutAd.setVisibility(View.VISIBLE);
        ivBackground.setVisibility(View.GONE);

        mAdCountDownSecond = AD_SHOW_SECOND;
        mMsgHandler.sendEmptyMessageDelayed(MSG_CODE_AD_COUNT_DOWN, 1000);
    }

    @Click(R.id.open_ad_layout_jump)
    void skipAd() {
        toNextPage("");
    }

    @Click(R.id.open_ad_layout_backgroud)
    void openAd() {
        if (mCurrentUser.needLogin()) {
            if (mCurrentUser.hasLoggedIn() && !TextUtils.isEmpty(mAdUrl) && !mAdUrl.startsWith("#")) {
                toNextPage(mAdUrl);
            }
        } else if (!TextUtils.isEmpty(mAdUrl) && !mAdUrl.startsWith("#")) {
            toNextPage(mAdUrl);
        }
    }

    private class AppInfoSubscriber extends Subscriber<AppInfo> {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(strApiError);
            delayToFinishApp();
        }

        @Override
        public void onNext(AppInfo appInfo) {
            mCurrentUser.setAppInfo(appInfo);
            mCurrentUser.setLink("");
            mCurrentUser.setChannelInfo("");

            if ("Show".equals(appInfo.ShowStartAd)) {
                mApiHelper.startAd(new StartAdSubscriber());
            } else {
                delayToNextPage();
            }
        }
    }

    private class StartAdSubscriber extends Subscriber<AdInfo> {

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(strApiError);
        }

        @Override
        public void onNext(AdInfo adInfo) {
            if (adInfo != null) {

                // 测试数据
//                adInfo.Total = 1;
//                AdInfo.AdDetail adDetail = new AdInfo.AdDetail();
//                adDetail.setUrl("#");
//                adDetail.setImage("http://fzmy.app3.baiyinet.com/App_Attachment/UnAuth/SDP_StartAdImage/1.jpg");
//                ArrayList<AdInfo.AdDetail> list = new ArrayList<>();
//                list.add(adDetail);
//                adInfo.setData(list);

                if (adInfo.getData() != null && adInfo.getTotal() > 0) {
                    initAdInfo(adInfo);
                } else {
                    initBaiduAd();
                }
            } else {
                delayToNextPage();
            }
        }
    }
}
